import {
  changeCurrentIndexAndSongAction,
  changeSequence,
  fetchPlayerAction,
} from "@/store/modules/player";
import { formatData } from "@/utils/fomatData";
import { fomatImgSizeY } from "@/utils/formatImgSize";
import { playMusic } from "@/utils/playMusic";
import {
  LeftCircleOutlined,
  PauseCircleOutlined,
  PlayCircleOutlined,
  RightCircleOutlined,
} from "@ant-design/icons";
import { Slider } from "antd";
import React, { memo, useCallback, useEffect, useRef, useState } from "react";
import { shallowEqual, useDispatch, useSelector } from "react-redux";
import { Control, Operator, PlayerWrapper, PlayInfo } from "./style";

const Player = memo(() => {
  // 实时播放时间
  const [currentTime, setCurrentTime] = useState(0);
  // 进度条拖拽，解决音乐播放冲突问题
  const [isChanging, setIsChanging] = useState(false);
  // 进度条时间
  const [progress, setProgress] = useState(0);
  // 判断音乐是否播放
  const [isPlaying, setIsPlaying] = useState(false);
  const { songDetails, sequence } = useSelector(
    (state) => ({
      songDetails: state.player.songDetails,
      sequence: state.player.sequence,
    }),
    shallowEqual
  );
  const dispatch = useDispatch();
  // 生命周期--歌曲的id
  useEffect(() => {
    // 固定数据
    // dispatch(fetchPlayerAction(411214279));
    audioRef.current.src = playMusic(songDetails?.id);
    // 选中音乐播放，切换歌曲不自动播放
    audioRef.current
      .play()
      .then((res) => {
        setIsPlaying(true);
      })
      .catch((err) => {
        setIsPlaying(false);
      });
  }, [songDetails]);

  // ref值
  const audioRef = useRef();

  // 一些值，处理undefind问题
  const singerName = (songDetails.ar && songDetails.ar[0].name) || "未知歌手";
  const duration = songDetails.dt || 0;
  const showCurrentTime = formatData(currentTime);

  // 判断播放还是暂停按钮
  const playCir = () => {
    if (!isPlaying) {
      return <PlayCircleOutlined style={{ color: "#fff", fontSize: "36px" }} />;
    } else {
      return (
        <PauseCircleOutlined style={{ color: "#fff", fontSize: "36px" }} />
      );
    }
  };

  // 点击播放音乐
  const playMic = useCallback(() => {
    isPlaying ? audioRef.current.pause() : audioRef.current.play();
    setIsPlaying(!isPlaying);
  }, [isPlaying]);

  // 实时播放时间的方法
  const timeUpdate = (e) => {
    if (!isChanging) {
      setCurrentTime(e.target.currentTime * 1000);
      setProgress((currentTime / duration) * 100);
    }
  };

  // 进度条拖拽
  const sliderChange = useCallback(
    (value) => {
      setIsChanging(true);
      setCurrentTime((value / 100) * duration);
      setProgress(value);
    },
    [duration]
  );
  const sliderAfterChange = useCallback(
    (value) => {
      const currentTime = ((value / 100) * duration) / 1000;
      audioRef.current.currentTime = currentTime;
      setCurrentTime(currentTime * 1000);
      setIsChanging(false);
    },
    [duration]
  );

  // 右边功能按钮--循环播放
  // 不同状态下显示按钮的样式
  const loopElement = useCallback(() => {
    if (sequence === 0) {
      return (
        <img
          className="ShunCursor"
          src={require("@/assets/icons/播放-循环播放.png")}
          alt=""
        />
      );
    } else if (sequence === 1) {
      return (
        <img
          className="ShunCursor"
          src={require("@/assets/icons/循环播放.png")}
          alt=""
        />
      );
    } else {
      return (
        <img
          className="ShunCursor"
          src={require("@/assets/icons/27F单次循环播放.png")}
          alt=""
        />
      );
    }
  }, [sequence]);
  const loop = () => {
    let currentSequence = sequence + 1;
    if (currentSequence > 2) {
      currentSequence = 0;
    }
    dispatch(changeSequence(currentSequence));
  }

  // 切换歌曲方法
  const changeMusic = (tag) => {
    dispatch(changeCurrentIndexAndSongAction(tag));
  };
  // 歌曲播放完自动切换歌曲
  const handleMusicEnded = () => {
    if (sequence === 2) {
      //单曲循环
      audioRef.current.currentTime = 0;
      audioRef.current.play();
    } else {
      dispatch(changeCurrentIndexAndSongAction(1));
    }
  };

  return (
    <PlayerWrapper className="sprite_player">
      <div className="content wrap-v2">
        <Control>
          <LeftCircleOutlined
            style={{ color: "#fff", fontSize: "28px" }}
            className="ShunCursor"
            onClick={(e) => changeMusic(-1)}
          />
          <div className="ShunCursor" onClick={(e) => playMic()}>
            {playCir()}
          </div>
          <RightCircleOutlined
            onClick={(e) => changeMusic(1)}
            style={{ color: "#fff", fontSize: "28px" }}
            className="ShunCursor"
          />
        </Control>
        <PlayInfo className="ShunCursor">
          <img src={fomatImgSizeY(songDetails?.al?.picUrl, 35)} alt="" />
          <div className="right">
            <div className="top">
              {songDetails?.name}&nbsp;&nbsp;&nbsp;&nbsp;{singerName}
            </div>
            <div className="bottom">
              <Slider
                defaultValue={30}
                value={progress}
                onChange={sliderChange}
                onAfterChange={sliderAfterChange}
              />
              <div className="time">
                <span>{showCurrentTime}</span>&nbsp;/&nbsp;
                <span className="playtime">{formatData(duration)}</span>
              </div>
            </div>
          </div>
        </PlayInfo>
        <Operator>
          <div className="left">
            <img
              className="ShunCursor"
              src={require("@/assets/icons/画中画.png")}
              alt=""
            />
            <img
              className="ShunCursor"
              src={require("@/assets/icons/24gl-folderPlus.png")}
              alt=""
            />
            <img
              className="ShunCursor"
              src={require("@/assets/icons/分享.png")}
              alt=""
            />
          </div>
          <div className="divier"> | </div>
          <div className="right">
            <img
              className="ShunCursor"
              src={require("@/assets/icons/扬声器.png")}
              alt=""
            />
            <div
              style={{ width: "22px", height: "22px" }}
              onClick={(e) => loop()}
            >
              {loopElement()}
            </div>
            <img
              className="ShunCursor"
              src={require("@/assets/icons/文件-播放列表.png")}
              alt=""
            />
          </div>
        </Operator>
      </div>
      <audio
        ref={audioRef}
        onTimeUpdate={(e) => timeUpdate(e)}
        onEnded={(e) => handleMusicEnded()}
      ></audio>
    </PlayerWrapper>
  );
});

export default Player;
